package com.bungarus.smart.busi;

import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;


@ChannelHandler.Sharable
public class ProcessMessageHandler extends ChannelInboundHandlerAdapter {
    Logger logger = Logger.getLogger(ProcessMessageHandler.class);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof MessageProtobuf.Message) {
            MessageProtobuf.Message message = (MessageProtobuf.Message) msg;
            switch(message.getHeader().getType()){
                case MessageType.HEARTBEAT_PONG:
                    //get pong
                    logger.info("Pong message received."); // from " + ((MessageProtobuf.Message) msg).getHeader().getFrom());
                    break;
                default:
                    logger.info("Response message is " + msg.toString());
                    break;
            }
        }
        else {
            super.channelRead(ctx, msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warn("One Access connection terminated !");
        ctx.close();
    }
}
